import autolog from "autolog.js"
import $ from "jquery"
import type { PlasmoCSConfig } from "plasmo"

import DomUtil from "~lib/dom"
import Grapper from "~lib/grapper"
import RecodeUtil from "~lib/recode"
import { sleep } from "~lib/util"

export const config: PlasmoCSConfig = {
  matches: ["https://market.m.taobao.com/app/alsc-medicine/huatuo/*"]
}

async function updateData(params: any[]) {
  try {
    const response = await fetch(
      "https://asst.jhjk.com.cn/api/collect/eleRxData",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(params)
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    return result
  } catch (error) {
    console.error("Error uploading data:", error)
    throw error
  }
}

// 封装获取处方数据的函数
async function fetchPrescriptions(type) {
  try {
    await DomUtil.selectChannel(type)

    await DomUtil.clickQueryBtn()

    let allPrescriptions = []

    let prescriptions = await Grapper.getCurrentPageInfo()
    if (!prescriptions?.length) {
      console.warn(`当前页面未获取到数据: ${type}`)
      return
    }

    allPrescriptions = allPrescriptions.concat(prescriptions)

    while (DomUtil.shouldClickNextPage(prescriptions, type)) {
      await DomUtil.clickNextPage()
      prescriptions = await Grapper.getCurrentPageInfo()
      allPrescriptions = allPrescriptions.concat(prescriptions)
    }

    if (allPrescriptions.length === 0) {
      console.warn(`未获取到任何数据: ${type}`)
      return
    }

    RecodeUtil.recodeLastData(allPrescriptions[0], type == "先方" ? 1 : 2)

    const filterList = allPrescriptions.filter(
      (item) => item.inquiryConsumeTime >= 60
    )

    if (filterList.length > 0) {
      const tmp = await updateData(filterList)
      const message = `${type} 初始数据量: ${allPrescriptions.length}; 过滤后数据量: ${filterList.length}; 接口上传结果：${tmp?.message || "未知unknown"}`

      autolog.log(message, "info")
    } else {
      console.info(`${type}: 无符合条件的数据需要上传`)
    }
  } catch (error) {
    console.error(`Error in ${type}:`, error)
    throw error
  }
}

$(async () => {
  try {
    await sleep(2000)
    await DomUtil.selectMenu()
    await sleep(1000)
    await await DomUtil.selectPageSize()
    for (const type of ["先方", "新先方"]) {
      console.info(`开始执行抓取上传任务: ${type}`)
      await fetchPrescriptions(type)
    }
  } catch (error) {
    console.error("执行失败:", error)
  }
})
